{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "initial_id",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-26T12:42:35.871922Z",
     "start_time": "2025-02-26T12:42:35.207033Z"
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "451a1dc184a6f2f9",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T13:50:49.902259Z",
     "start_time": "2025-02-10T13:50:49.898167Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "1  2.0   None    B\n",
      "2  3.0   None    C\n",
      "3  NaN    bbb    D\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 下面是一个单级索引的DataFrame结构\n",
    "df = pd.DataFrame({'Age': [1,2,3,None,5], \n",
    "                  'Reason':['aaa',None,None,'bbb','ccc'], \n",
    "                  \"Deck\":['A','B','C','D','E']},\n",
    "                 columns=['Age','Reason','Deck'])\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "53d8a48b9e5becfc",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T13:52:07.656395Z",
     "start_time": "2025-02-10T13:52:07.651281Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "index1     a1      a2    \n",
      "index2    mk1 mk2 mk1 mk2\n",
      "col1 col2                \n",
      "c1   tk1   11  10  16   7\n",
      "     tk2    7   1   4  10\n",
      "c2   tk1   18  14  18   1\n",
      "     tk2    5  15   3   2\n"
     ]
    }
   ],
   "source": [
    "# 下面创建一个具有多级索引的DataFrame结构\n",
    "index_1 = pd.MultiIndex.from_product([['c1','c2'],['tk1','tk2']],\n",
    "                                     names=['col1','col2'])\n",
    "index_2 = pd.MultiIndex.from_product([['a1','a2'],['mk1','mk2']],\n",
    "                                     names=['index1','index2'])\n",
    "\n",
    "data = pd.DataFrame(np.random.randint(0,20,size=(4,4)),\n",
    "                    index=index_1,\n",
    "                    columns=index_2)\n",
    "\n",
    "print(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ea77f86800e333c",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "### 1. pd.drop函数的使用方法 \n",
    "DataFrame.drop(labels, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4127a419cbe0ecfa",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T13:38:49.949290Z",
     "start_time": "2025-02-10T13:38:49.943956Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Reason\n",
      "0    aaa\n",
      "1   None\n",
      "2   None\n",
      "3    bbb\n",
      "4    ccc\n",
      "   Age Reason Deck\n",
      "1  2.0   None    B\n",
      "2  3.0   None    C\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 去掉数组特定的列\n",
    "df_drop_1 = df.drop(labels=['Age','Deck'], axis=1)  # 删除特定列，等价于：df.drop(columns=['Age','Deck'])\n",
    "df_drop_2 = df.drop(labels=[0,3], axis=0)  # 删除特定行，等价于：df.drop(index=[0,3])\n",
    "print(df_drop_1)\n",
    "print(df_drop_2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "affdf2475542b3a2",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T13:44:50.145161Z",
     "start_time": "2025-02-10T13:44:50.140161Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "2  3.0   None    C\n",
      "3  NaN    bbb    D\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 在原始数组的基础上进行修改\n",
    "df.drop(labels=[1], axis=0, inplace=True)\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "76fec98acc140503",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T13:57:26.735033Z",
     "start_time": "2025-02-10T13:57:26.726941Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "index1     a1      a2    \n",
      "index2    mk1 mk2 mk1 mk2\n",
      "col1 col2                \n",
      "c1   tk1   11   3  13  19\n",
      "     tk2   11  18   2  19\n",
      "c2   tk1    0   8   9   9\n",
      "     tk2   14  16   2   0 \n",
      " =============================\n",
      "index1     a1      a2    \n",
      "index2    mk1 mk2 mk1 mk2\n",
      "col1 col2                \n",
      "c2   tk1    0   8   9   9\n",
      "     tk2   14  16   2   0\n",
      "index1     a1  a2\n",
      "index2    mk2 mk2\n",
      "col1 col2        \n",
      "c1   tk1    3  19\n",
      "     tk2   18  19\n",
      "c2   tk1    8   9\n",
      "     tk2   16   0\n"
     ]
    }
   ],
   "source": [
    "# 删除多级索引的行或者列\n",
    "print(data,'\\n', '=============================')\n",
    "\n",
    "data_drop_1 = data.drop(labels=['c1'], level='col1', axis=0)\n",
    "print(data_drop_1)\n",
    "\n",
    "data_drop_2 = data.drop(labels=['mk1'], level='index2', axis=1)  # 需要加上这个axis参数\n",
    "print(data_drop_2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd8a36ce5a56f222",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "ab40ff5ad33db091",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "### 2、pd.dropna函数的用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "7f3ce6475de4192a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T14:01:47.506762Z",
     "start_time": "2025-02-10T14:01:47.503720Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "1  2.0   None    B\n",
      "2  3.0   None    C\n",
      "3  NaN    bbb    D\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 沿用df数组\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "8a18859f7f5f8a3f",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T14:02:11.578530Z",
     "start_time": "2025-02-10T14:02:11.575447Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 删掉所有包含None值的行\n",
    "df_na = df.dropna()\n",
    "print(df_na)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "48ebbb62a205256b",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T14:06:08.816538Z",
     "start_time": "2025-02-10T14:06:08.813040Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Deck\n",
      "0    A\n",
      "1    B\n",
      "2    C\n",
      "3    D\n",
      "4    E\n"
     ]
    }
   ],
   "source": [
    "# 删掉所有包含None的列（等价于使用参数any）\n",
    "df_na = df.dropna(axis=1, how=\"any\")\n",
    "print(df_na)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "8c5d802d14e311ff",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T14:06:47.159585Z",
     "start_time": "2025-02-10T14:06:47.155494Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "1  2.0   None    B\n",
      "2  3.0   None    C\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 删掉某一列中有None值的所有行\n",
    "df_na = df.dropna(subset=['Age'], axis=0)\n",
    "print(df_na)  # 第4行没了"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "53cfd57e1ee66c50",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T14:07:04.590120Z",
     "start_time": "2025-02-10T14:07:04.586119Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Deck\n",
      "0  1.0    A\n",
      "1  2.0    B\n",
      "2  3.0    C\n",
      "3  NaN    D\n",
      "4  5.0    E\n"
     ]
    }
   ],
   "source": [
    "# 删掉某一行中有None值的所有的列\n",
    "df_na = df.dropna(subset=[2],axis=1)\n",
    "print(df_na)  # 第4行没了"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "162488721268b89b",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "687c741b524748dd",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "### 3、pd.fillna函数的使用方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "f1233a6aea71a29f",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T14:14:58.821155Z",
     "start_time": "2025-02-10T14:14:58.817155Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "1  2.0   None    B\n",
      "2  3.0   None    C\n",
      "3  NaN    bbb    D\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 还是使用数组ddf\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "ab944c47a96dea5d",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T14:15:51.873150Z",
     "start_time": "2025-02-10T14:15:51.869732Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "1  2.0   -3.0    B\n",
      "2  3.0   -3.0    C\n",
      "3 -3.0    bbb    D\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 直接用固定数组填充所有的None值\n",
    "df_fillna = df.fillna(value=-3.0)\n",
    "print(df_fillna)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "b4b549024011f6ba",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T14:17:04.649510Z",
     "start_time": "2025-02-10T14:17:04.645510Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    Age Reason Deck\n",
      "0  1.00    aaa    A\n",
      "1  2.00   None    B\n",
      "2  3.00   None    C\n",
      "3  2.75    bbb    D\n",
      "4  5.00    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 用每一列的平均值来填充每一列的空值\n",
    "df_fillna = df.fillna({\"Age\":np.mean(df['Age'])})\n",
    "print(df_fillna)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5fcc019c-1f67-433d-8a6a-cee3fd10a2a6",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-10T14:19:00.622336Z",
     "start_time": "2025-02-10T14:19:00.617276Z"
    },
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "### 4、iloc函数的用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4fa2f352-7206-4e5c-8d1d-8073b9360aa6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e8794d29-b144-46da-b995-e241c7a17497",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>A</th>\n",
       "      <th>B</th>\n",
       "      <th>C</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>s1</th>\n",
       "      <td>9</td>\n",
       "      <td>0</td>\n",
       "      <td>16</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>s2</th>\n",
       "      <td>17</td>\n",
       "      <td>5</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>s3</th>\n",
       "      <td>17</td>\n",
       "      <td>8</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     A  B   C\n",
       "s1   9  0  16\n",
       "s2  17  5   2\n",
       "s3  17  8   7"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = pd.DataFrame(np.random.randint(0,20,(3,3)), columns=[\"A\",\"B\",\"C\"], index=[\"s1\",\"s2\",\"s3\"])\n",
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f34fe5c4-51b4-4784-ab16-64275d1f09f4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "np.int32(5)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 使用iloc对行和列进行索引某个元素\n",
    "data.iloc[1, 1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "460a9c0f-8db7-4a5a-a139-f657ea6b47ec",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "s1     9\n",
       "s2    17\n",
       "s3    17\n",
       "Name: A, dtype: int32"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 索引特定的列\n",
    "data.iloc[:, 0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "dd696933-6af3-4a96-82f6-56e2f516f65b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "A     9\n",
       "B     0\n",
       "C    16\n",
       "Name: s1, dtype: int32"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 单个索引默认是行\n",
    "data.iloc[0] # 等价于data.iloc[0, :]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5fbcfb2b-1548-47cf-a5e4-98839aa5a082",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "np.int32(9)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 先索引行，再索引列\n",
    "data.iloc[0]['A']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d3946205-7e0e-4ed1-b88f-0e3c4449a3de",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "6cff5dae69c18594",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "### 5、pd.fillna函数的使用方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "a825da90c8f5c2ea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "1  2.0   None    B\n",
      "2  3.0   None    C\n",
      "3  NaN    bbb    D\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 还是使用数组ddf\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "2332d1354a6532b0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "1  2.0   -3.0    B\n",
      "2  3.0   -3.0    C\n",
      "3 -3.0    bbb    D\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 直接用固定数组填充所有的None值\n",
    "df_fillna = df.fillna(value=-3.0)\n",
    "print(df_fillna)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "f0260b07eee91794",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    Age Reason Deck\n",
      "0  1.00    aaa    A\n",
      "1  2.00   None    B\n",
      "2  3.00   None    C\n",
      "3  2.75    bbb    D\n",
      "4  5.00    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 用每一列的平均值来填充每一列的空值\n",
    "df_fillna = df.fillna({\"Age\":np.mean(df['Age'])})\n",
    "print(df_fillna)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "5eb722090f0ae85f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "print(1+1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ee971cee36e7b30",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "578d94558c8162a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a0c42f0218070966",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "1  2.0   None    B\n",
      "2  3.0   None    C\n",
      "3  NaN    bbb    D\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 下面是一个单级索引的DataFrame结构\n",
    "df = pd.DataFrame({'Age': [1,2,3,None,5], \n",
    "                  'Reason':['aaa',None,None,'bbb','ccc'], \n",
    "                  \"Deck\":['A','B','C','D','E']},\n",
    "                 columns=['Age','Reason','Deck'])\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "72a4c7e68827f6a8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "index1     a1      a2    \n",
      "index2    mk1 mk2 mk1 mk2\n",
      "col1 col2                \n",
      "c1   tk1   18  13   3  19\n",
      "     tk2   16  19   4  19\n",
      "c2   tk1   17  10   7  10\n",
      "     tk2    7  13  10   3\n"
     ]
    }
   ],
   "source": [
    "# 下面创建一个具有多级索引的DataFrame结构\n",
    "index_1 = pd.MultiIndex.from_product([['c1','c2'],['tk1','tk2']],\n",
    "                                     names=['col1','col2'])\n",
    "index_2 = pd.MultiIndex.from_product([['a1','a2'],['mk1','mk2']],\n",
    "                                     names=['index1','index2'])\n",
    "\n",
    "data = pd.DataFrame(np.random.randint(0,20,size=(4,4)),\n",
    "                    index=index_1,\n",
    "                    columns=index_2)\n",
    "\n",
    "print(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c22de431747a5058",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Reason\n",
      "0    aaa\n",
      "1   None\n",
      "2   None\n",
      "3    bbb\n",
      "4    ccc\n",
      "   Age Reason Deck\n",
      "1  2.0   None    B\n",
      "2  3.0   None    C\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 去掉数组特定的列\n",
    "df_drop_1 = df.drop(labels=['Age','Deck'], axis=1)  # 删除特定列，等价于：df.drop(columns=['Age','Deck'])\n",
    "df_drop_2 = df.drop(labels=[0,3], axis=0)  # 删除特定行，等价于：df.drop(index=[0,3])\n",
    "print(df_drop_1)\n",
    "print(df_drop_2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "715d606ca0b76fec",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "2  3.0   None    C\n",
      "3  NaN    bbb    D\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 在原始数组的基础上进行修改\n",
    "df.drop(labels=[1], axis=0, inplace=True)\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "46915a8512481c91",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "index1     a1      a2    \n",
      "index2    mk1 mk2 mk1 mk2\n",
      "col1 col2                \n",
      "c1   tk1   11   3  13  19\n",
      "     tk2   11  18   2  19\n",
      "c2   tk1    0   8   9   9\n",
      "     tk2   14  16   2   0 \n",
      " =============================\n",
      "index1     a1      a2    \n",
      "index2    mk1 mk2 mk1 mk2\n",
      "col1 col2                \n",
      "c2   tk1    0   8   9   9\n",
      "     tk2   14  16   2   0\n",
      "index1     a1  a2\n",
      "index2    mk2 mk2\n",
      "col1 col2        \n",
      "c1   tk1    3  19\n",
      "     tk2   18  19\n",
      "c2   tk1    8   9\n",
      "     tk2   16   0\n"
     ]
    }
   ],
   "source": [
    "# 删除多级索引的行或者列\n",
    "print(data,'\\n', '=============================')\n",
    "\n",
    "data_drop_1 = data.drop(labels=['c1'], level='col1', axis=0)\n",
    "print(data_drop_1)\n",
    "\n",
    "data_drop_2 = data.drop(labels=['mk1'], level='index2', axis=1)  # 需要加上这个axis参数\n",
    "print(data_drop_2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "90c64ad660a48412",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "62dc67e1d5482382",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "1  2.0   None    B\n",
      "2  3.0   None    C\n",
      "3  NaN    bbb    D\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 沿用df数组\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "7c7208ee97dd3ed2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 删掉所有包含None值的行\n",
    "df_na = df.dropna()\n",
    "print(df_na)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "5d834eb94467c207",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  Deck\n",
      "0    A\n",
      "1    B\n",
      "2    C\n",
      "3    D\n",
      "4    E\n"
     ]
    }
   ],
   "source": [
    "# 删掉所有包含None的列（等价于使用参数any）\n",
    "df_na = df.dropna(axis=1, how=\"any\")\n",
    "print(df_na)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "36a4b580385b3d4a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "1  2.0   None    B\n",
      "2  3.0   None    C\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 删掉某一列中有None值的所有行\n",
    "df_na = df.dropna(subset=['Age'],axis=0)\n",
    "print(df_na)  # 第4行没了"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "18020f6b932c68d9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Deck\n",
      "0  1.0    A\n",
      "1  2.0    B\n",
      "2  3.0    C\n",
      "3  NaN    D\n",
      "4  5.0    E\n"
     ]
    }
   ],
   "source": [
    "# 删掉某一行中有None值的所有的列\n",
    "df_na = df.dropna(subset=[2],axis=1)\n",
    "print(df_na)  # 第4行没了"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cdc128851e248f3e",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "d4e53d51cd4180c6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "1  2.0   None    B\n",
      "2  3.0   None    C\n",
      "3  NaN    bbb    D\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 还是使用数组ddf\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "14c7e57800b7b162",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age Reason Deck\n",
      "0  1.0    aaa    A\n",
      "1  2.0   -3.0    B\n",
      "2  3.0   -3.0    C\n",
      "3 -3.0    bbb    D\n",
      "4  5.0    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 直接用固定数组填充所有的None值\n",
    "df_fillna = df.fillna(value=-3.0)\n",
    "print(df_fillna)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "7f02b8754a691d7e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    Age Reason Deck\n",
      "0  1.00    aaa    A\n",
      "1  2.00   None    B\n",
      "2  3.00   None    C\n",
      "3  2.75    bbb    D\n",
      "4  5.00    ccc    E\n"
     ]
    }
   ],
   "source": [
    "# 用每一列的平均值来填充每一列的空值\n",
    "df_fillna = df.fillna({\"Age\":np.mean(df['Age'])})\n",
    "print(df_fillna)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "9eb69bb0340dee98",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "print(1+1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "36aecf0dcc426d4f",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "3f2380900001fa83",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "### 下面是Titanic这个库涉及的函数的进一步学习"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9a6cb0d136769bee",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b55ccaf7b1c68de",
   "metadata": {},
   "source": [
    "<img src=\"\\python-py-qt-test2\\Titanic_Learning.png\"  width=\"800\" height=\"auto\">"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6cf348ae16dfd42d",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "### 1. 列联表函数pd.crosstab的用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "81887044be73315f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前表格为：\n",
      "    班级  学科  分数\n",
      "0  张三  物理  77\n",
      "1  张三  物理  90\n",
      "2  张三  数学  78\n",
      "3  李四  数学  82\n",
      "4  李四  外语  66\n",
      "5  李四  政治  70\n",
      "6  王五  物理  90\n",
      "7  王五  政治  60\n"
     ]
    }
   ],
   "source": [
    "# 表格的含义为：学生每次参加的考试情况和分数，注意张三考了两次物理\n",
    "data = {\n",
    "    '班级': ['张三', '张三', '张三', '李四','李四','李四','王五', '王五'],\n",
    "    '学科': ['物理', '物理','数学', '数学', '外语', '政治', '物理', '政治'],\n",
    "    '分数': [77, 90, 78, 82, 66, 70, 90, 60]\n",
    "}\n",
    "df = pd.DataFrame(data)\n",
    "print(\"当前表格为：\\n\", df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "7a6fe2f435e1e08f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "学生考试的情况为：\n",
      " 学科  外语  政治  数学  物理\n",
      "班级                \n",
      "张三   0   0   1   2\n",
      "李四   1   1   1   0\n",
      "王五   0   1   0   1\n"
     ]
    }
   ],
   "source": [
    "# 使用 pd.crosstab 计算 A 和 B 的交叉表\n",
    "crosstab = pd.crosstab(df['班级'], df['学科'])  # 聚合前两列，默认计算频次值\n",
    "print(\"学生考试的情况为：\\n\" ,crosstab)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "5108e02c06a894d7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "学生选择的科目为：\n",
      " 学科    外语    政治    数学    物理\n",
      "班级                        \n",
      "张三   NaN   NaN  78.0  83.5\n",
      "李四  66.0  70.0  82.0   NaN\n",
      "王五   NaN  60.0   NaN  90.0\n"
     ]
    }
   ],
   "source": [
    "# 使用 pd.crosstab 计算 A 和 B 的交叉表\n",
    "crosstab = pd.crosstab(df['班级'], df['学科'], values=df['分数'], aggfunc='mean')\n",
    "print(\"学生选择的科目为：\\n\" ,crosstab)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d2a356e1c003080",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "### 2.分组函数groupby的用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "63f8d6dc02a41bac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   班级  学科  分数\n",
      "0  张三  物理  77\n",
      "1  张三  物理  90\n",
      "2  张三  数学  78\n",
      "3  李四  数学  82\n",
      "4  李四  外语  66\n",
      "5  李四  政治  70\n",
      "6  王五  物理  90\n",
      "7  王五  政治  60\n"
     ]
    }
   ],
   "source": [
    "# 选用上面的那个数据集\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "b052d76a82a7af6f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "班级\n",
       "张三    81.666667\n",
       "李四    72.666667\n",
       "王五    75.000000\n",
       "Name: 分数, dtype: float64"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 输出几个人所有成绩的平均分\n",
    "df.groupby(['班级'])['分数'].mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "bdf0c9932ee7ecb8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>班级</th>\n",
       "      <th>学科</th>\n",
       "      <th>分数</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>张三</td>\n",
       "      <td>物理</td>\n",
       "      <td>77</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>张三</td>\n",
       "      <td>物理</td>\n",
       "      <td>90</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>张三</td>\n",
       "      <td>数学</td>\n",
       "      <td>78</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>李四</td>\n",
       "      <td>数学</td>\n",
       "      <td>82</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>李四</td>\n",
       "      <td>外语</td>\n",
       "      <td>66</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>李四</td>\n",
       "      <td>政治</td>\n",
       "      <td>70</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>王五</td>\n",
       "      <td>物理</td>\n",
       "      <td>90</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>王五</td>\n",
       "      <td>政治</td>\n",
       "      <td>60</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   班级  学科  分数\n",
       "0  张三  物理  77\n",
       "1  张三  物理  90\n",
       "2  张三  数学  78\n",
       "3  李四  数学  82\n",
       "4  李四  外语  66\n",
       "5  李四  政治  70\n",
       "6  王五  物理  90\n",
       "7  王五  政治  60"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 输出几个人每门学科的平均分\n",
    "df.groupby(['班级','学科'])['分数'].mean()\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "3a984b768a115a05",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>平均值</th>\n",
       "      <th>最大值</th>\n",
       "      <th>最小值</th>\n",
       "      <th>标准差</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>班级</th>\n",
       "      <th>学科</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">张三</th>\n",
       "      <th>数学</th>\n",
       "      <td>78.0</td>\n",
       "      <td>78</td>\n",
       "      <td>78</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>物理</th>\n",
       "      <td>83.5</td>\n",
       "      <td>90</td>\n",
       "      <td>77</td>\n",
       "      <td>9.192388</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"3\" valign=\"top\">李四</th>\n",
       "      <th>外语</th>\n",
       "      <td>66.0</td>\n",
       "      <td>66</td>\n",
       "      <td>66</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>政治</th>\n",
       "      <td>70.0</td>\n",
       "      <td>70</td>\n",
       "      <td>70</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>数学</th>\n",
       "      <td>82.0</td>\n",
       "      <td>82</td>\n",
       "      <td>82</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">王五</th>\n",
       "      <th>政治</th>\n",
       "      <td>60.0</td>\n",
       "      <td>60</td>\n",
       "      <td>60</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>物理</th>\n",
       "      <td>90.0</td>\n",
       "      <td>90</td>\n",
       "      <td>90</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        平均值  最大值  最小值       标准差\n",
       "班级 学科                          \n",
       "张三 数学  78.0   78   78       NaN\n",
       "   物理  83.5   90   77  9.192388\n",
       "李四 外语  66.0   66   66       NaN\n",
       "   政治  70.0   70   70       NaN\n",
       "   数学  82.0   82   82       NaN\n",
       "王五 政治  60.0   60   60       NaN\n",
       "   物理  90.0   90   90       NaN"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 输出几个人每门学科的平均分、最高分、最低分、中位数，方差值\n",
    "dc = df.groupby(['班级','学科'])['分数'].agg(['mean','max', 'min', 'std'])\n",
    "dc.columns = [\"平均值\", \"最大值\", \"最小值\", \"标准差\"]\n",
    "dc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "4dbc02e0bcab2b2e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "MultiIndex([('张三', '数学'),\n",
       "            ('张三', '物理'),\n",
       "            ('李四', '外语'),\n",
       "            ('李四', '政治'),\n",
       "            ('李四', '数学'),\n",
       "            ('王五', '政治'),\n",
       "            ('王五', '物理')],\n",
       "           names=['班级', '学科'])"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dc.index"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f61941c5480a1fb",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "### 3.修改DataFrame的值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "id": "d39d591d4236a6dd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>A1</th>\n",
       "      <th>A2</th>\n",
       "      <th>A3</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3</td>\n",
       "      <td>Alice</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>5</td>\n",
       "      <td>Alice</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>9</td>\n",
       "      <td>Alice</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2</td>\n",
       "      <td>Alice</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>4</td>\n",
       "      <td>Bob</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>1</td>\n",
       "      <td>Bob</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   A1     A2  A3\n",
       "0   3  Alice   1\n",
       "1   5  Alice   2\n",
       "2   9  Alice   1\n",
       "3   2  Alice   2\n",
       "4   4    Bob   1\n",
       "5   1    Bob   2"
      ]
     },
     "execution_count": 72,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = {\n",
    "    \"A1\":np.random.randint(0,10,(6,)),\n",
    "    \"A2\":['Alice'] * 4 + [\"Bob\"] * 2,\n",
    "    \"A3\":[1,2] * 3\n",
    "}\n",
    "\n",
    "df = pd.DataFrame(data)\n",
    "df.index = range(0, 6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "7a847ea170d5cf92",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>A1</th>\n",
       "      <th>A2</th>\n",
       "      <th>A3</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3</td>\n",
       "      <td>Alice</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>5</td>\n",
       "      <td>Alice</td>\n",
       "      <td>-20</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>9</td>\n",
       "      <td>Alice</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2</td>\n",
       "      <td>Alice</td>\n",
       "      <td>-20</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>4</td>\n",
       "      <td>Bob</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>1</td>\n",
       "      <td>Bob</td>\n",
       "      <td>-20</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   A1     A2  A3\n",
       "0   3  Alice  10\n",
       "1   5  Alice -20\n",
       "2   9  Alice  10\n",
       "3   2  Alice -20\n",
       "4   4    Bob  10\n",
       "5   1    Bob -20"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 修改特定列的元素\n",
    "df['A3'] = df['A3'].map({1:10,2:-20})\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "id": "acfcbbd0b10d532f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    2\n",
       "1    4\n",
       "2    8\n",
       "3    1\n",
       "4    3\n",
       "5    0\n",
       "Name: A1, dtype: int64"
      ]
     },
     "execution_count": 84,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 使用匿名函数将特定列的元素 - 1\n",
    "df3 = df['A1'].map(lambda x: x -1)\n",
    "df3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "id": "bef8888c7345934d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    3\n",
       "1    3\n",
       "2    3\n",
       "3    3\n",
       "4    3\n",
       "5    3\n",
       "Name: A2, dtype: int64"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 字符串改为数值\n",
    "df4 = df['A2'].map(lambda x: 3)\n",
    "df4"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3252ce75af1c8318",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "### 4.哑变量函数pd.get_dummies的用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "5c1155b62225dcbd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>学科</th>\n",
       "      <th>分数</th>\n",
       "      <th>姓名&amp;张三</th>\n",
       "      <th>姓名&amp;李四</th>\n",
       "      <th>姓名&amp;王五</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>物理</td>\n",
       "      <td>77</td>\n",
       "      <td>True</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>物理</td>\n",
       "      <td>90</td>\n",
       "      <td>True</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>数学</td>\n",
       "      <td>78</td>\n",
       "      <td>True</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>数学</td>\n",
       "      <td>82</td>\n",
       "      <td>False</td>\n",
       "      <td>True</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>外语</td>\n",
       "      <td>66</td>\n",
       "      <td>False</td>\n",
       "      <td>True</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>政治</td>\n",
       "      <td>70</td>\n",
       "      <td>False</td>\n",
       "      <td>True</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>物理</td>\n",
       "      <td>90</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>True</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>政治</td>\n",
       "      <td>60</td>\n",
       "      <td>False</td>\n",
       "      <td>False</td>\n",
       "      <td>True</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   学科  分数  姓名&张三  姓名&李四  姓名&王五\n",
       "0  物理  77   True  False  False\n",
       "1  物理  90   True  False  False\n",
       "2  数学  78   True  False  False\n",
       "3  数学  82  False   True  False\n",
       "4  外语  66  False   True  False\n",
       "5  政治  70  False   True  False\n",
       "6  物理  90  False  False   True\n",
       "7  政治  60  False  False   True"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 将“班级”一列中的数据转化为哑变量，同时设置哑变量列的前缀、原变量名之间的符号\n",
    "df_dummies = pd.get_dummies(df, columns=[\"班级\"], prefix=\"姓名\", prefix_sep=\"&\")\n",
    "df_dummies"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62e0fce2bd7f042d",
   "metadata": {},
   "source": [
    "### 5.随机森林函数的使用方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "5d508d2c594b3789",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 1.00\n"
     ]
    }
   ],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.datasets import load_iris\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import accuracy_score\n",
    "\n",
    "# 加载数据集\n",
    "iris = load_iris()\n",
    "X, y = iris.data, iris.target\n",
    "\n",
    "# 划分训练集和测试集\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
    "\n",
    "# 初始化随机森林分类器\n",
    "rf_clf = RandomForestClassifier(n_estimators=100, criterion='gini', random_state=42)\n",
    "\n",
    "# 训练模型\n",
    "rf_clf.fit(X_train, y_train)\n",
    "\n",
    "# 进行预测\n",
    "y_pred = rf_clf.predict(X_test)\n",
    "\n",
    "# 计算准确率\n",
    "accuracy = accuracy_score(y_test, y_pred)\n",
    "print(f\"Accuracy: {accuracy:.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "b327a3a6f18b54bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier  # 导入随机森林函数\n",
    "from sklearn.datasets import load_iris  # 导入数据集\n",
    "from sklearn.model_selection import train_test_split  # 导入训练集划分函数\n",
    "from sklearn.metrics import accuracy_score  # 导入准确性计算函数\n",
    "\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "22c4caa279eaab3f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(150, 4) (150,)\n",
      "[[5.1 3.5 1.4 0.2]\n",
      " [4.9 3.  1.4 0.2]\n",
      " [4.7 3.2 1.3 0.2]\n",
      " [4.6 3.1 1.5 0.2]\n",
      " [5.  3.6 1.4 0.2]\n",
      " [5.4 3.9 1.7 0.4]\n",
      " [4.6 3.4 1.4 0.3]\n",
      " [5.  3.4 1.5 0.2]\n",
      " [4.4 2.9 1.4 0.2]\n",
      " [4.9 3.1 1.5 0.1]]\n",
      "[0 0 0 0 0 0 0 0 0 0]\n"
     ]
    }
   ],
   "source": [
    "# 加载数据集\n",
    "iris = load_iris()\n",
    "X, y = iris.data, iris.target\n",
    "\n",
    "print(X.shape, y.shape)\n",
    "print(X[:10, :])\n",
    "print(y[:10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "f9f4a6e9a399aea8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(105, 4) (45, 4) (105,) (45,)\n"
     ]
    }
   ],
   "source": [
    "# 划分训练集和测试集\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
    "\n",
    "print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "36f3c04521cb8169",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-1 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: #000;\n",
       "  --sklearn-color-text-muted: #666;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-1 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-1 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-1 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: flex;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "  align-items: start;\n",
       "  justify-content: space-between;\n",
       "  gap: 0.5em;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label .caption {\n",
       "  font-size: 0.6rem;\n",
       "  font-weight: lighter;\n",
       "  color: var(--sklearn-color-text-muted);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-1 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-1 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-1 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-1 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-1 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 0.5em;\n",
       "  text-align: center;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-1 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>RandomForestClassifier(random_state=42)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow\"><div><div>RandomForestClassifier</div></div><div><a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.6/modules/generated/sklearn.ensemble.RandomForestClassifier.html\">?<span>Documentation for RandomForestClassifier</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></div></label><div class=\"sk-toggleable__content fitted\"><pre>RandomForestClassifier(random_state=42)</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "RandomForestClassifier(random_state=42)"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 初始化随机森林分类器\n",
    "rf_clf = RandomForestClassifier(n_estimators=100, criterion='gini', random_state=42)\n",
    "\n",
    "# 训练模型\n",
    "rf_clf.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "c140c026e6c3aa68",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 0, 2, 1, 1, 0, 1, 2, 1, 1, 2, 0, 0, 0, 0, 1, 2, 1, 1, 2, 0, 2,\n",
       "       0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 1, 0, 0, 2, 1, 0, 0, 0, 2, 1, 1, 0,\n",
       "       0])"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 利用拟合模型进行预测\n",
    "y_pred = rf_clf.predict(X_test)\n",
    "y_pred"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "2cb209989c30aaec",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 1.00\n"
     ]
    }
   ],
   "source": [
    "# 计算准确率\n",
    "accuracy = accuracy_score(y_test, y_pred)\n",
    "print(f\"Accuracy: {accuracy:.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "633ff40645f96642",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
